﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Minestorm.Evolved.IoC
{
	public class SingletonCache : IDisposable
	{
		private Dictionary<Type, Object> _dictionary = new Dictionary<Type, Object>();

		public SingletonCache() { }

		public void CacheSingletonInstance<I>(I instance)
			where I : class
		{
			CacheSingletonInstance(typeof(I), instance);
		}

		public void CacheSingletonInstance(Type interfaceType, Object instance)
		{
			if (!_dictionary.ContainsKey(interfaceType))
				_dictionary.Add(interfaceType, instance);
		}

		public Boolean GetInstance(Type interfaceType, out Object instance)
		{
			return _dictionary.TryGetValue(interfaceType, out instance);
		}

		public void RemoveInstance<I>()
			where I : class
		{
			Object instance;

			if (_dictionary.TryGetValue(typeof(I), out instance))
			{
				_dictionary.Remove(typeof(I));

				if (instance is IDisposable)
					((IDisposable)instance).Dispose();
			}
		}

		public void Dispose()
		{
			foreach (Object instance in _dictionary.Values)
				if (instance is IDisposable)
					((IDisposable)instance).Dispose();
		}

		public void Clear()
		{
			_dictionary.Clear();
		}
	}
}
